package com.putao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.putao.base.BaseService;
import com.putao.domain.SysDictItem;
import com.putao.mapper.SysDictItemMapper;
import com.putao.service.SysDictItemService;
import com.putao.utils.AssertUtil;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 字典具体的选项值表 服务实现类
 * </p>
 *
 * @author putao
 * @since 2022-02-09
 */
@Service
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService, BaseService<SysDictItem> {

    @Override
    public SysDictItem saveDictItem(SysDictItem dictItem) {
        AssertUtil.hasText(dictItem.getItemText(), "字典项文本不能为空");
        AssertUtil.hasText(dictItem.getItemValue(), "字典项值不能为空");
        this.checkIsEmptyAndRepeat(null, new QueryWrapper<>(), dictItem, "item_text", "字典项文本称重复了", "字典项文本不能为空");
        this.checkIsEmptyAndRepeat(null, new QueryWrapper<>(), dictItem, "item_value", "字典项值重复了", "字典项值不能为空");
//        dict.insertInit();
//        this.save(dict);
//        return dict;
        QueryWrapper<SysDictItem> wrapper = new QueryWrapper<>();
        SysDictItem sysDictItem = this.getOne(wrapper.eq("dict_id", dictItem.getDictId()).orderByDesc("item_value").last("limit 1"));
        if(sysDictItem != null ) {
            int itemValue = Integer.parseInt(sysDictItem.getItemValue()) + 1;
            dictItem.setItemValue(Integer.toString(itemValue));
            dictItem.setSortOrder(sysDictItem.getSortOrder() + 1);
        }else {
            dictItem.setItemValue("1");
            dictItem.setSortOrder(1);
        }
        dictItem.insertInit();
        this.save(dictItem);
        return dictItem;
    }
}
